using System;
using System.Threading;

namespace MediaWikiEngine.Domain
{
	/// <summary>
	/// Keeps the consumer of <see cref="RequestLimiter.WaitForTimeout"/> waiting until the timeout limit passes.
	/// </summary>
	/// <remarks>Not thread-safe.</remarks>
	public class RequestLimiter
	{
		DateTime _lastRequest = DateTime.MinValue;
		TimeSpan _limit;

		public RequestLimiter()
		{
			_limit = new TimeSpan(0,0,1);
		}

		public RequestLimiter(TimeSpan limit)
		{
			_limit = limit;			
		}

		public bool RequestAllowed
		{
			get 
			{
				if (DateTime.Now.Subtract(_lastRequest) > _limit)
					return true;

				return false;
			}
		}

		public void RecordRequest()
		{
			_lastRequest = DateTime.Now;
		}

		public void WaitForTimeout()
		{
			TimeSpan cycle = new TimeSpan(0, 0, 1);

			while (false == RequestAllowed)
			{
				Thread.Sleep(cycle);
			}

			RecordRequest();
		}


	}
}
